import cn from 'classnames';
import PropTypes from 'prop-types';
import React from 'react';
import Tooltip from '@kuiper-components/tooltip';
import copy from 'copy-to-clipboard';
import notification from '@kuiper-components/notification';

import s from './style.module.css';

function CopyBoard({
	className,
	text,
	maxWidth,
	overlay = (
		<p className={s.copyBoardOverlay}>
			<span className={cn(s.content)}>{text}</span>点击即可复制
		</p>
	),
}) {
	const nodeRef = React.useRef();
	const handleCopyText = () => {
		if (copy(nodeRef?.current?.innerText)) {
			notification.success({
				message: '内容已复制！',
				style: { width: '13rem' },
				placement: 'top',
			});
		} else {
			notification.error({
				message: '内容复制失败，请手动复制。',
				placement: 'top',
			});
		}
	};

	return (
		<Tooltip placement="top" overlay={overlay}>
			<span
				className={cn(className, s.copyBoard)}
				ref={nodeRef}
				onClick={handleCopyText}
				style={{ maxWidth }}
			>
				{text}
			</span>
		</Tooltip>
	);
}

CopyBoard.propTypes = {
	className: PropTypes.string,
	text: PropTypes.string,
	overlay: PropTypes.node,
};
CopyBoard.defaultProps = {
	className: '',
};

export default CopyBoard;
